package com.zyc.transfrom;

import com.lowagie.text.pdf.BaseFont;  
import org.xhtmlrenderer.pdf.ITextFontResolver;  
import org.xhtmlrenderer.pdf.ITextRenderer;  
  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.OutputStream;  
  
/** 
 * Created by Carey on 15-2-2. 
 */  
public class Html2Pdf {  
    public boolean convertHtmlToPdf(String inputFile, String outputFile)  
            throws Exception {  
    	//String outputParentFolder = outputFile.substring(0, outputFile.lastIndexOf(Word2Html.FILE_SEPARATOR));
    	String sPicSavePath = inputFile.replace(".html", "");
    	System.out.println("sPicSavePath= " + sPicSavePath);
        OutputStream os = new FileOutputStream(outputFile);  
        ITextRenderer renderer = new ITextRenderer();  
        String url = new File(inputFile).toURI().toURL().toString();  
        renderer.setDocument(url);  
        // 解决中文支持问题  
        ITextFontResolver fontResolver = renderer.getFontResolver();  
        fontResolver.addFont("./simsunb.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);  
        //解决图片的相对路径问题  
        System.out.println(sPicSavePath.replace("\\", "/"));
        renderer.getSharedContext().setBaseURL("file:/" + sPicSavePath.replace("\\", "/"));  
        System.out.println(sPicSavePath);
        try {
        	renderer.layout();
        	renderer.createPDF(os); 
		} catch (Exception e) {
			e.printStackTrace();
		}  
         
        os.flush();  
        os.close();  
        return true;  
    }  
  
  
     public   static  void  main(String [] args){  
         Html2Pdf html2Pdf =new Html2Pdf();  
         try {  
             html2Pdf.convertHtmlToPdf("D:\\11.html","D:\\index.pdf");  
         } catch (Exception e) {  
             e.printStackTrace();  
         }  
     }  
}  